import sys
from . import barplot
from pathlib import Path

args = sys.argv[1: ]
current_path = Path.cwd()
model_path = Path(__file__).parent
help_text = '''
          python -m format_sciplot init [plot_type] 生成默认配置文件
          python -m format_sciplot draw [plot_type] <数据文件路径> <数据模板路径> [-to <输出文件夹>](可选) [-use <配置文件路径>](可选)

          plot_type:
          - barplot 柱状图
          - lineplot 折线图
          '''
default_data_schema_path = model_path / 'data_schema.toml'
default_config_path = {
    'barplot': model_path / 'barplot.toml',
    'lineplot': model_path / 'lineplot.toml'
}
draw_function = {
    'barplot': barplot.draw_from_cli
}
status = None
plot_type = None

if {'h', 'help', '-h', '--h', '-help', '--help'} & set(args):
    print(help_text)
    exit()
else:
    try:
        match args.pop(0):
            case 'init':
                status = 'init'
                plot_type = args.pop(0)
            case 'draw':
                status = 'draw'
                plot_type = args.pop(0)

                data_file = args.pop(0)
                data_file = data_file if Path(data_file).is_absolute() else current_path / data_file

                data_schema = args.pop(0)
                data_schema = data_schema if Path(data_schema).is_absolute() else current_path / data_schema

                output_path = current_path / 'output'
                config_path = model_path / 'barplot.toml'

                while args:
                    match args.pop(0):
                        case '-to':
                            output_path = args.pop(0)
                            output_path = output_path if Path(output_path).is_absolute() else current_path / output_path
                        case '-use':
                            config_path = args.pop(0)
                            config_path = config_path if Path(config_path).is_absolute() else current_path / config_path
                        case _:
                            raise Exception()
            case _:
                raise Exception()
    except:
        print('错误指令')
        print(help_text)
        exit()

if plot_type not in default_config_path:
    print(f'{plot_type} 类型错误')
    exit()

match status:
    case 'init':
        (current_path / f'{plot_type}.toml').write_bytes(default_config_path[plot_type].read_bytes())
        if not (current_path / 'data_schema.toml').exists():
            (current_path / 'data_schema.toml').write_bytes(default_data_schema_path.read_bytes())
        else:
            print('当前目录已存在data_schema.toml')
        print('已在当前目录下生成配置文件')
        exit()
    case 'draw':
        output_path.mkdir(parents=True, exist_ok=True)
        draw_function[plot_type](data_file, data_schema, output_path, config_path, current_path)
        print('完成')